﻿using System;
using System.Collections.Generic;
using System.Globalization;
using System.IO;
using System.Linq;
using System.Text;
using System.Web.Mvc;
using EPiBoost.Core.Model.TemplateParameters;
using EPiServer.Core;
using EPiServer.DataAbstraction;
using EPiServer.Framework.Localization;
using EPiServer.Framework.Serialization;
using EPiServer.Framework.Web;
using EPiServer.ServiceLocation;
using System;
using System.Collections.Generic;
using System.Runtime.CompilerServices;
using System.Runtime.InteropServices;
using System.Web;
using EPiServer.Web;
using EPiServer.Web.Mvc;
using EPiServer.Web.Mvc.Html;

namespace EPiBoost.Core.Web.Mvc.Html
{

	public static class ContentAreaExtensionsOld
	{
		// Methods
		public static MvcHtmlString ContentArea(this HtmlHelper html, ContentArea contentArea)
		{
			return html.ContentArea(contentArea, html.ViewContext.HttpContext.GetService<IContentRenderer>(null),
			                        html.ViewContext.HttpContext.GetService<ITemplateResolver>(null),
			                        html.ViewContext.HttpContext.GetService<ObjectSerializerFactory>(null),
			                        LocalizationService.Current);
		}

		public static MvcHtmlString ContentArea(this HtmlHelper html, ContentArea contentArea,
		                                        IContentRenderer contentRenderer, ITemplateResolver templateResolver,
		                                        ObjectSerializerFactory objectSerializerFactory,
		                                        LocalizationService localizationService)
		{
			return HtmlString.GetMvcHtmlString(delegate(TextWriter writer)
			                                   	{
			                                   		html.RenderContentArea(contentArea, contentRenderer,
			                                   		                       templateResolver,
			                                   		                       objectSerializerFactory,
			                                   		                       localizationService);
			                                   	});
		}

		private static bool EditMode(HtmlHelper html)
		{
			return (html.ViewContext.RequestContext.RouteData.DataTokens["contextmode"].ToString() == "Edit");
		}

		public static void RenderContentArea(this HtmlHelper html, ContentArea contentArea)
		{
			html.RenderContentArea(contentArea, html.ViewContext.HttpContext.GetService<IContentRenderer>(null),
			                       html.ViewContext.HttpContext.GetService<ITemplateResolver>(null),
			                       html.ViewContext.HttpContext.GetService<ObjectSerializerFactory>(null),
			                       LocalizationService.Current);
		}

		public static void RenderContentArea(this HtmlHelper html, ContentArea contentArea, IContentRenderer contentRenderer,
		                                     ITemplateResolver templateResolver,
		                                     ObjectSerializerFactory objectSerializerFactory,
		                                     LocalizationService localizationService)
		{
			if ((contentArea == null) || contentArea.IsEmpty)
			{
				if (EditMode(html))
				{
					html.ViewContext.Writer.Write(localizationService.GetString("/edit/contentarea/empty"));
				}
			}
			else
			{
				int i = 0; 
				int total = contentArea.Contents.Count();

				var wrapperSettings = Helpers.LoadWrapperSetttings(html);
				var rowSettings = Helpers.LoadRowSetttings(html);


				foreach (IContent content in contentArea.Contents)
				{
					TemplateModel templateModel = templateResolver.Resolve(html.ViewContext.HttpContext, content,
					                                                       TemplateTypeCategories.MvcPartial,
					                                                       html.ViewContext.ViewData["tag"] as string);
					if (EditMode(html))
					{
						html.ViewContext.Writer.Write(string.Format(CultureInfo.InvariantCulture, "<div {0}=\"{1}\"{2}>",
						                                            new object[]
						                                            	{
						                                            		"data-epi-block-id", content.ContentLink.ToString(),
						                                            		RenderInfoAttribute(templateModel, objectSerializerFactory)
						                                            	}));
					}

					Helpers.TryOpenRow(html, rowSettings, i, total);

					bool wrapperOpen = Helpers.OpenWrapper(html, wrapperSettings, i, total, rowSettings);

					html.RenderContentData(content, true, templateModel, contentRenderer);

					if (wrapperOpen)
					{
						Helpers.CloseWrapper(html, wrapperSettings);
					}

					Helpers.TryCloseRow(html, rowSettings, i, total);

					if (EditMode(html))
					{
						html.ViewContext.Writer.Write("</div>");
					}

					i++;
				}
			}
		}


		private static string RenderInfoAttribute(TemplateModel templateModel, ObjectSerializerFactory objectSerializerFactory)
		{
			if (templateModel != null)
			{
				return string.Empty;
			}
			System.Collections.Generic.Dictionary<string, object> dictionary = new System.Collections.Generic.Dictionary<string, object>();
			dictionary.Add("missingrenderer", "true");
			IObjectSerializer serializer = objectSerializerFactory.GetSerializer("application/json");
			System.Text.StringBuilder builder = new System.Text.StringBuilder();
			serializer.Serialize(new System.IO.StringWriter(builder), dictionary);
			return string.Format(System.Globalization.CultureInfo.InvariantCulture, "{0}='{1}'", new object[] { "data-epi-block-info", builder.ToString() });
		}
	}
}

  
 
